package com.demo.controller;

import com.demo.domain.User;
import com.demo.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/user/save")
public class UserSaveController extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //将接收和发送的参数改编码格式
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        //跨域请求，响应
        resp.setHeader("Access-Control-Allow-Origin", "*");//允许所以域的主机访问
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        resp.setHeader("Access-Control-Allow-Headers","*");//允许所有请求头访问
        if (req.getMethod().equals("OPTIONS")) {
            resp.setStatus(200);
            return;
        }
        //获取接收的参数值
        //将传输的JSon串转回字符串
        User user = objectMapper.readValue(req.getReader(), User.class);
        //创建spring容器
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = context.getBean("userService", UserService.class);
        boolean b= userService.save(user);
        System.out.println("UserSaveController.service===>b"+b);
        resp.getWriter().print(b?"成功":"失败");
    }
}
